<template>
  <view class="detail-container">
    <!-- 状态卡片 -->
    <view class="status-card" :class="statusClass">
      <uni-icons :type="statusIcon" size="60" color="#fff"></uni-icons>
      <view class="status-text">{{ statusText }}</view>
      <view v-if="detail.auditStatus !== '0'" class="audit-info">
        <text>审核人：{{ detail.auditBy }}</text>
        <text>审核时间：{{ detail.auditTime }}</text>
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="info-section">
      <view class="section-title">基本信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="label">预约编号</text>
          <text class="value">{{ detail.applyNo }}</text>
        </view>
        <view class="info-item">
          <text class="label">商户名称</text>
          <text class="value">{{ detail.merchantName }}</text>
        </view>
        <view class="info-item">
          <text class="label">联系人</text>
          <text class="value">{{ detail.contactPerson }}</text>
        </view>
        <view class="info-item">
          <text class="label">联系电话</text>
          <text class="value">{{ detail.contactPhone }}</text>
        </view>
        <view class="info-item">
          <text class="label">入场时间</text>
          <text class="value">{{ detail.entryTime }}</text>
        </view>
        <view class="info-item">
          <text class="label">入场地点</text>
          <text class="value">{{ detail.entryPlace }}</text>
        </view>
        <view class="info-item">
          <text class="label">车牌号</text>
          <text class="value">{{ detail.vehicleNo }}</text>
        </view>
      </view>
    </view>

    <!-- 商品明细 -->
    <view class="info-section">
      <view class="section-title">商品明细</view>
      <view class="goods-list">
        <view v-for="(goods, index) in detail.appointmentDetailList" :key="index" class="goods-item">
          <view class="goods-header">
            <text class="goods-name">{{ goods.goodsName }}</text>
            <!-- <view v-if="goods.needInspection" class="inspect-badge">需抽检</view> -->
          </view>
          <view class="goods-info">
            <view class="goods-detail">
              <text>数量：{{ goods.quantity }}{{ goods.unit }}</text>
              <text>产地：{{ goods.originPlace || '产地未知'}}</text>
            </view>
            <view v-if="goods.supplierName" class="goods-detail">
              <text>供货商：{{ goods.supplierName }}</text>
            </view>
          </view>
		  <!-- 资质图片显示区域 -->
		  <view class="product-qualifications">
		  	<view class="qualifications-title">产品资质</view>
		  	<view class="qualifications-container">
		  		<!-- 进货凭证 -->
		  		<view class="qualification-item" v-if="goods.purchaseVoucher">
		  			<text class="qualification-label">进货凭证</text>
		  			<image :src="goods.purchaseVoucher" mode="aspectFill" class="qualification-image"
		  				@click="previewImage1(goods.purchaseVoucher)"></image>
		  		</view>
		  
		  		<!-- 承诺达标合格证 -->
		  		<view class="qualification-item" v-if="goods.qualificationCert">
		  			<text class="qualification-label">承诺达标合格证</text>
		  			<image :src="goods.qualificationCert" mode="aspectFill" class="qualification-image"
		  				@click="previewImage1(goods.qualificationCert)"></image>
		  		</view>
		  
		  		<!-- 动物检疫合格证明 -->
		  		<view class="qualification-item" v-if="goods.animalQuarantineCert">
		  			<text class="qualification-label">动物检疫合格证明</text>
		  			<image :src="goods.animalQuarantineCert" mode="aspectFill" class="qualification-image"
		  				@click="previewImage1(goods.animalQuarantineCert)"></image>
		  		</view>
		  
		  		<!-- 肉品品质检验合格证 -->
		  		<view class="qualification-item" v-if="goods.meatQualityCert">
		  			<text class="qualification-label">肉品品质检验合格证</text>
		  			<image :src="goods.meatQualityCert" mode="aspectFill" class="qualification-image"
		  				@click="previewImage1(goods.meatQualityCert)"></image>
		  		</view>
		  	</view>
		  </view>
		  
        </view>
      </view>
    </view>

    <!-- 凭证信息 -->
    <view class="info-section" v-if="detail.certificates && detail.certificates.length > 0">
      <view class="section-title">相关凭证</view>
      <view class="cert-list">
        <view v-for="(cert, index) in detail.certificates" :key="index" class="cert-item" @click="previewImage(cert)">
          <image :src="cert.url" mode="aspectFill" class="cert-image"></image>
          <text class="cert-name">{{ cert.name }}</text>
        </view>
      </view>
    </view>

    <!-- 审核意见 -->
    <view class="info-section" v-if="detail.auditStatus !== '0' && detail.auditComment">
      <view class="section-title">审核意见</view>
      <view class="audit-comment">
        {{ detail.auditComment }}
      </view>
    </view>

    <!-- 审核操作 - 仅待审核状态显示 -->
    <view v-if="detail.auditStatus === '0'" class="bottom-actions">
      <view class="action-btn reject-btn" @click="handleReject">
        <uni-icons type="close-filled" size="20" color="#fff"></uni-icons>
        <text>拒绝</text>
      </view>
      <view class="action-btn inspect-btn" @click="handleInspect">
        <uni-icons type="eye-filled" size="20" color="#fff"></uni-icons>
        <text>需抽检</text>
      </view>
      <view class="action-btn pass-btn" @click="handlePass">
        <uni-icons type="checkbox-filled" size="20" color="#fff"></uni-icons>
        <text>通过</text>
      </view>
    </view>

    <!-- 审核弹窗 -->
    <uni-popup ref="auditPopup" type="bottom" background-color="#fff">
      <view class="audit-popup">
        <view class="popup-header">
          <text class="popup-title">{{ auditTitle }}</text>
          <uni-icons type="closeempty" size="24" @click="closeAuditPopup"></uni-icons>
        </view>
        <view class="popup-content">
          <view class="popup-section">
            <text class="popup-label">审核意见{{ auditType === '3' ? '（必填）' : '（选填）' }}</text>
            <textarea 
              v-model="auditComment" 
              :placeholder="auditPlaceholder"
              class="audit-textarea"
              maxlength="200"
            ></textarea>
          </view>
          
          <!-- 需抽检时选择商品 -->
          <view v-if="auditType === '2'" class="popup-section">
            <text class="popup-label">选择需要抽检的商品（必选）</text>
            <checkbox-group @change="handleGoodsChange">
              <label v-for="goods in detail.appointmentDetailList" :key="goods.detailId" class="goods-checkbox">
                <checkbox :value="goods.detailId" :checked="selectedGoods.includes(goods.detailId)" />
                <view class="checkbox-content">
                  <text class="goods-name">{{ goods.goodsName }}</text>
                  <text class="goods-qty">{{ goods.quantity }}{{ goods.unit }}</text>
                </view>
              </label>
            </checkbox-group>
          </view>
        </view>
        <view class="popup-footer">
          <button class="btn-cancel" @click="closeAuditPopup">取消</button>
          <button class="btn-confirm" :class="confirmBtnClass" @click="confirmAudit">确认{{ auditBtnText }}</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getAppointment, auditAppointment } from '@/api/business/appointment.js'

export default {
  data() {
    return {
      applyId: '',
      detail: {
        auditStatus: '0',
        appointmentDetailList: [],
        certificates: []
      },
      // 审核相关
      auditType: '', // 1-通过 2-需抽检 3-拒绝
      auditComment: '',
      selectedGoods: []
    }
  },
  computed: {
    // 状态卡片样式
    statusClass() {
      const statusMap = {
        '0': 'pending',
        '1': 'pass',
        '2': 'inspect',
        '3': 'reject'
      }
      return statusMap[this.detail.auditStatus] || 'pending'
    },
    // 状态图标
    statusIcon() {
      const iconMap = {
        '0': 'eye',
        '1': 'checkbox-filled',
        '2': 'eye-filled',
        '3': 'close-filled'
      }
      return iconMap[this.detail.auditStatus] || 'eye'
    },
    // 状态文本
    statusText() {
      const textMap = {
        '0': '待审核',
        '1': '审核通过',
        '2': '需要抽检',
        '3': '审核拒绝'
      }
      return textMap[this.detail.auditStatus] || '待审核'
    },
    // 审核弹窗标题
    auditTitle() {
      const titleMap = {
        '1': '通过审核',
        '2': '标记需抽检',
        '3': '拒绝审核'
      }
      return titleMap[this.auditType] || '审核'
    },
    // 审核占位符
    auditPlaceholder() {
      const placeholderMap = {
        '1': '请输入审核通过意见（选填）',
        '2': '请输入需要抽检的原因（选填）',
        '3': '请输入拒绝原因（必填）'
      }
      return placeholderMap[this.auditType] || '请输入审核意见'
    },
    // 确认按钮样式
    confirmBtnClass() {
      const classMap = {
        '1': 'btn-pass',
        '2': 'btn-inspect',
        '3': 'btn-reject'
      }
      return classMap[this.auditType] || ''
    },
    // 审核按钮文本
    auditBtnText() {
      const textMap = {
        '1': '通过',
        '2': '标记',
        '3': '拒绝'
      }
      return textMap[this.auditType] || '确认'
    }
  },
  onLoad(options) {
    this.applyId = options.id
    this.loadDetail()
  },
  methods: {
	  // 预览图片
	  previewImage1(imageUrl) {
	  	if (imageUrl) {
	  		uni.previewImage({
	  			urls: [imageUrl],
	  			current: 0
	  		})
	  	}
	  },
    // 加载详情
    async loadDetail() {
      if (!this.applyId) {
        uni.showToast({
          title: '参数错误',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const res = await getAppointment(this.applyId)
        
        if (res.code === 200 && res.data) {
          this.detail = res.data
          // 处理凭证图片
          if (this.detail.certificateUrls) {
            this.detail.certificates = this.detail.certificateUrls.split(',').map((url, index) => ({
              url: url,
              name: `凭证${index + 1}`
            }))
          }
          
          // 确保有商品列表
          if (!this.detail.appointmentDetailList) {
            this.detail.appointmentDetailList = []
          }
        }
      } catch (error) {
        console.error('加载详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 预览图片
    previewImage(cert) {
      uni.previewImage({
        urls: this.detail.certificates.map(c => c.url),
        current: cert.url
      })
    },
    
    // 通过
    handlePass() {
      this.auditType = '1'
      this.auditComment = ''
      this.$refs.auditPopup.open()
    },
    
    // 需抽检
    handleInspect() {
      this.auditType = '2'
      this.auditComment = ''
      this.selectedGoods = []
      this.$refs.auditPopup.open()
    },
    
    // 拒绝
    handleReject() {
      this.auditType = '3'
      this.auditComment = ''
      this.$refs.auditPopup.open()
    },
    
    // 选择商品
    handleGoodsChange(e) {
      this.selectedGoods = e.detail.value
    },
    
    // 关闭弹窗
    closeAuditPopup() {
      this.$refs.auditPopup.close()
      this.auditComment = ''
      this.selectedGoods = []
    },
    
    // 确认审核
    async confirmAudit() {
      // 验证
      if (this.auditType === '3' && !this.auditComment) {
        uni.showToast({
          title: '请填写拒绝原因',
          icon: 'none'
        })
        return
      }
      
      if (this.auditType === '2' && this.selectedGoods.length === 0) {
        uni.showToast({
          title: '请选择需要抽检的商品',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '提交中...'
      })
      
      try {
        const data = {
          applyId: this.applyId,
          auditStatus: this.auditType,
          auditComment: this.auditComment
        }
        
        if (this.auditType === '2') {
          data.inspectionDetailIds = this.selectedGoods
        }
        
        const res = await auditAppointment(data)
        if (res.code === 200) {
          uni.showToast({
            title: '审核成功',
            icon: 'success'
          })
          this.closeAuditPopup()
          
          // 延迟返回列表
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }
      } catch (error) {
        uni.showToast({
          title: '审核失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
  }
}
</script>

<style scoped>
	/* 产品资质样式 */
	.product-qualifications {
		padding: 20rpx 0;
		border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
	}
	
	.qualifications-title {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 15rpx;
	}
	
	.qualifications-container {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}
	
	.qualification-item {
		flex: 1;
		min-width: 45%;
	}
	
	.qualification-label {
		display: block;
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
	}
	
	.qualification-image {
		width: 100%;
		height: 150rpx;
		border-radius: 8rpx;
		border: 1rpx solid #e6e6e6;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	.verify-container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.status-header {
		padding: 60rpx 30rpx;
		text-align: center;
		color: #fff;
	}
	
	.status-loading {
		background: linear-gradient(135deg, #667eea, #764ba2);
	}
	
	.status-success {
		background: linear-gradient(135deg, #52c41a, #73d13d);
	}
	
	.status-warning {
		background: linear-gradient(135deg, #faad14, #ffc53d);
	}
	
	.status-error {
		background: linear-gradient(135deg, #ff4d4f, #ff7875);
	}
	
	.status-checked {
		background: linear-gradient(135deg, #13c2c2, #36cfc9);
	}
	
	.status-icon {
		margin-bottom: 30rpx;
	}
	
	.status-title {
		font-size: 40rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.status-desc {
		font-size: 28rpx;
		opacity: 0.9;
	}
	
	.info-card,
	.goods-card {
		background-color: #fff;
		margin: 20rpx;
		border-radius: 12rpx;
		padding: 30rpx;
	}
	
	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f0f0f0;
	}
	
	.card-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	
	.qr-badge {
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: bold;
		color: #fff;
	}
	
	.badge-green {
		background-color: #52c41a;
	}
	
	.badge-yellow {
		background-color: #faad14;
	}
	
	.badge-red {
		background-color: #ff4d4f;
	}
	
	.info-list {
		/* 信息列表样式 */
	}
	
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}
	
	.info-item:last-child {
		border-bottom: none;
	}
	
	.info-label {
		font-size: 28rpx;
		color: #666;
	}
	
	.info-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
	}
	
	.status-checked {
		color: #52c41a;
	}
	
	.status-unchecked {
		color: #faad14;
	}
	
	.inspection-alert {
		display: flex;
		align-items: center;
		background-color: #fffbe6;
		border: 2rpx solid #ffe58f;
		border-radius: 8rpx;
		margin: 20rpx;
		padding: 20rpx;
	}
	
	.expired-alert {
		display: flex;
		align-items: center;
		background-color: #fff1f0;
		border: 2rpx solid #ffccc7;
		border-radius: 8rpx;
		margin: 20rpx;
		padding: 20rpx;
	}
	
	.expired-alert .alert-text {
		margin-left: 15rpx;
		font-size: 28rpx;
		color: #cf1322;
	}
	
.detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 180rpx;
}

/* 状态卡片 */
.status-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 30rpx;
  color: #fff;
	background-color: #13c2c2;
}

.status-card.pending {
  background: linear-gradient(135deg, #fa8c16, #ffa940);
}

.status-card.passed {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.status-card.inspect {
  background: linear-gradient(135deg, #faad14, #ffd666);
}

.status-card.rejected {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.status-text {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 20rpx;
}

.audit-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 30rpx;
  font-size: 26rpx;
  opacity: 0.9;
}

.audit-info text {
  margin-bottom: 10rpx;
}

/* 信息区块 */
.info-section {
  background: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
  padding-left: 12rpx;
  border-left: 4rpx solid #1890ff;
}

.info-list {
  display: flex;
  flex-direction: column;
}

.info-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  width: 180rpx;
  color: #999;
  font-size: 28rpx;
}

.value {
  flex: 1;
  color: #333;
  font-size: 28rpx;
}

/* 商品列表 */
.goods-list {
  display: flex;
  flex-direction: column;
}

.goods-item {
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
}

.goods-item:last-child {
  margin-bottom: 0;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.goods-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.inspect-badge {
  background: #faad14;
  color: #fff;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 4rpx;
}

.goods-info {
  font-size: 26rpx;
  color: #666;
}

.goods-detail {
  margin-bottom: 10rpx;
}

.goods-detail text {
  margin-right: 30rpx;
}

/* 凭证列表 */
.cert-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.cert-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: calc(33.33% - 14rpx);
}

.cert-image {
  width: 100%;
  height: 200rpx;
  border-radius: 8rpx;
  background: #f0f0f0;
}

.cert-name {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
}

/* 审核意见 */
.audit-comment {
  padding: 20rpx;
  background: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

/* 底部操作 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.95), #fff);
  backdrop-filter: blur(10px);
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  height: 90rpx;
  border-radius: 24rpx;
  font-size: 30rpx;
  font-weight: 600;
  transition: all 0.3s;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
}

.action-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.6s;
}

.action-btn:active {
  transform: translateY(2rpx) scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.action-btn:active::before {
  left: 100%;
}

.action-btn text {
  color: #fff;
  position: relative;
  z-index: 1;
  font-weight: 600;
}

.pass-btn {
  background: linear-gradient(135deg, #52c41a, #73d13d);
}

.pass-btn:active {
  background: linear-gradient(135deg, #389e0d, #52c41a);
}

.inspect-btn {
  background: linear-gradient(135deg, #faad14, #ffc53d);
}

.inspect-btn:active {
  background: linear-gradient(135deg, #d48806, #faad14);
}

.reject-btn {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
}

.reject-btn:active {
  background: linear-gradient(135deg, #cf1322, #ff4d4f);
}

/* 审核弹窗 */
.audit-popup {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 80vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.popup-section {
  margin-bottom: 30rpx;
}

.popup-label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.audit-textarea {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #f8f8f8;
}

.goods-checkbox {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.checkbox-content {
  margin-left: 20rpx;
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.goods-qty {
  color: #999;
  font-size: 26rpx;
}

.popup-footer {
  display: flex;
  padding: 30rpx;
  gap: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.popup-footer button {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 30rpx;
  border-radius: 12rpx;
  border: none;
}

.btn-cancel {
  background: #faad14;
  color: #fff;
}

.btn-confirm {
  color: #fff;
  background: #52c41a;
}

.confirm-pass {
  background: #52c41a;
}

.confirm-inspect {
  background: #faad14;
}

.confirm-reject {
  background: #ff4d4f;
}
</style>